package com.example.hotel.controller.user;

import com.example.hotel.bl.user.AccountService;
import com.example.hotel.po.User;
import com.example.hotel.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.security.PermitAll;

/**
 * @Author: zjy,xzh
 * @Date: 5-28
 */
@RestController()
@RequestMapping("/api/user")
public class AccountController {
    private final static String ACCOUNT_INFO_ERROR = "用户名或密码错误";
    @Autowired
    private AccountService accountService;

    /**
     * 注册到个人用户
     * 注意路径改变
     * @param userVO
     * @return
     */
    @PostMapping("/register/individual")
    public ResponseVO registerAccount(@RequestBody UserVO userVO) {
        return accountService.registerAccount(userVO);
    }

    /**
     * 注册到企业客户
     * 传入格式见UserEntVO
     * @param userEntVO
     * @return
     */

    @PostMapping("/register/enterprise")
    @PreAuthorize("hasPermission('client','normal')")
    public ResponseVO registerEntAccount(@RequestBody UserEntVO userEntVO) {
        return accountService.registerEntUser(userEntVO);
    }


    @GetMapping("/{id}/getUserInfo")
    @PreAuthorize("#id == (@accountServiceImpl.getIdByEmail(principal.username))")
    public ResponseVO getUserInfo(@PathVariable int id) {
        User user = accountService.getUserInfo(id);
        if(user==null){
            return ResponseVO.buildFailure(ACCOUNT_INFO_ERROR);
        }
        return ResponseVO.buildSuccess(user);
    }

    @PostMapping("/{id}/userInfo/update")
    @PreAuthorize("#id == (@accountServiceImpl.getIdByEmail(principal.username))")
    public ResponseVO updateInfo(@RequestBody UserInfoVO userInfoVO,@PathVariable int id){
        return accountService.updateUserInfo(id,userInfoVO.getPassword(),userInfoVO.getUserName(),userInfoVO.getPhoneNumber());
    }

    /**
     * 查看信用记录
     * @param id userId
     * @return resp
     */
    @GetMapping("/{id}/credit")
    @PreAuthorize("#id == (@accountServiceImpl.getIdByEmail(principal.username))")
    public ResponseVO getCreditInfo(@PathVariable int id) {
        return accountService.getUserCreditInfo(id);
    }



    //xzh
    //C.iii 信用充值
    //参数的形式不确定
    @PostMapping("/{id}/investCredit")
    @PreAuthorize("hasPermission('client','normal')")
    public ResponseVO investCredit(@PathVariable int id,@RequestParam double investedMoney)
    {
        return accountService.investCredit(id,investedMoney);
    };



    @PostMapping("/uploadImg/{userId}")
    @PermitAll
    public ResponseVO savePic(@RequestParam("file") MultipartFile file, @PathVariable Integer userId){
        return accountService.savePic(file,userId);
    }

    @GetMapping("/getImg/{userId}")
    @PermitAll
    public ResponseVO getPic(@PathVariable Integer userId){
        return accountService.getPic(userId);
    }

}
